#!/usr/bin/env python3
# Licensing : see licensing directory

import re
import misc

def phase2 (filelist):
    """This phase verify that all files have a good file statement and generates 
    the files tree."""
    print ("\nPhase #2: Files tree")
    
    # Describing the tree as a dictionnary of dictionnary, each one containing 
    # pairs of filepath and name
    filestree = {}
    filestree['Package'] = {}   
    filestree['Program'] = {}
    filestree['Sub'] = {}
    
    # We run a pass by file in filelist
    counter = 0                 # Setting up a passes counter
    for files in filelist:
        counter += 1
        print ("\tPass #"+str(counter)+': '+files)
        
        # We get the first line of the file, check for it not to be empty,
        # and then we print it to screen.
        try: 
            with open(files, 'r') as fd:
                firstline=(fd.readline()).rstrip()  # Remove the '\n' character at
                                                    # the end of the line (only
                                                    # usefull while we print it)
        except: 
            print("\t\tError: Can't read "+files+". Exiting")
            exit (1)
        if (not firstline):
            print ("\t\tError: The First line is empty. Exiting")
            exit (1)
        print ('\t\tFirst line: "'+firstline+'"')
        
        # We split the firstline into tokens, then we print them
        tokens=firstline.split()
        print ('\t\tTokens:' ,tokens)

        # I'm looking for a better way to perform the following test. By the
        # way, it works. 
        # The goal is to verify that there is an acceptable number of tokens,
        # and to check that they follow a simplified syntax.
        # Simplified syntax: 
        #       ('WORD WORD' or 'WORD WORD : WORD') + \
        #           ('' or '~' + ('' or 'SENTENCE'))
        #       Assuming that WORD is any kind of string with no spaces, and
        #       that SENTENCE is any kind of string.
        n = 0   #counter
        for t in tokens:
            "First syntaxic pass: number of tokens in the line"
            if (n == 2):
                if (t != ':'):
                    if (t != '~'):
                        print ("\t\tError: Unexpected number of tokens. Exiting")
                        exit (1)
                break
            elif (n == 4):
                if (t != '~'):
                    print ("\t\tError: Unexpected number of tokens. Exiting")
                    exit (1)
                break
            n += 1
        print ("\t\tDebug: Expected number of tokens")
        
        # I think this also might be optimized... Well now it works... 
        # I'll make it run fast later.
        # This, at each pass, parses the tokens, verify that they match with the
        # token's level grammar, and builds the tree. See output for doc on how
        # it is represented.
        if (tokens[0] == 'Package'):
            "We will verify the line grammar and build our tree"
            if (re.match(r'§\w+' ,tokens[1])):
                filestree['Package'][tokens[1]] = []
                filestree['Package'][tokens[1]].append(files)
            else:
                print ("\t\tError: Syntax error, file name not matching. Exiting")
                exit(1)
        elif (tokens[0] == 'Program'):
            if (re.match(r'§\w+' ,tokens[1])):
                filestree['Program'][tokens[1]] = []
                filestree['Program'][tokens[1]].append(files)
            else:
                print ("\t\tError: Syntax error, file name not matching. Exiting")
                exit(1)
        elif (tokens[0] == 'Sub'):
            if (tokens[2] == ':'):
                if (re.match(r'§\w+' ,tokens[1]) and re.match(r'§\w+', tokens[3])):
                    filestree['Sub'][tokens[1]] = []
                    filestree['Sub'][tokens[1]].append(files)
                    filestree['Sub'][tokens[1]].append(tokens[3])
                else:
                    print ("\t\tError: Syntax error, file name not matching. Exiting")
                    exit(1)
            else:
                print ("\t\tError: Syntax error, you must give a Program or a Package to the Sub. Exiting")
                exit(1)
        else:
            print ("\t\tError: token "+tokens[0]+" unexpected at that position. Exiting")
            exit (1)  
    
    
    # Would be great (till useless) to sort filestree here by keys at each 
    # level.
    
    # Printing filestree to screen in a readable way. Cf. parser output. This
    # code is a little bit obscure for a first read.
    print ("\n\tFiles tree:\n\t-----------")
    for i in filestree:
        print ("\t"+i+'s:')
        for j in filestree[i]:
            print ("\t\t"+j+':')
            tmp = 1
            for k in filestree[i][j]:
                if (tmp == 1):
                    if (i == 'Sub'): print ("\t\t\t"+k, end=' -> ')
                    else: print ("\t\t\t"+k)
                else:
                    print (k)
                tmp += 1
                
    return misc.fend(filestree)

